package org.jeecg.modules.bj.service.impl;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hpsf.Decimal;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.entity.SignTable;
import org.jeecg.modules.activiti.service.Impl.ActBusinessServiceImpl;
import org.jeecg.modules.activiti.service.SignTableService;
import org.jeecg.modules.bj.entity.*;
import org.jeecg.modules.bj.mapper.BjGwbdMapper;
import org.jeecg.modules.bj.mapper.BjQuitMapper;
import org.jeecg.modules.bj.mapper.BjYgruzhiMapper;
import org.jeecg.modules.bj.service.BjCreateFileService;
import org.jeecg.modules.bj.service.IBjIdcardfkService;
import org.jeecg.modules.bj.service.IBjRecruitmentApplicationService;
import org.jeecg.modules.bj.service.IYgdabService;
import org.jeecg.modules.bj.util.Constants;
import org.jeecg.modules.bj.util.ExcelExportUtil;
import org.jeecg.modules.bj.util.ExcelExportUtils;
import org.jeecg.modules.bj.util.PoiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BjCreateFileServiceImpl implements BjCreateFileService {
    @Autowired
    private IBjIdcardfkService bjIdcardfkService;
    @Autowired
    ActBusinessServiceImpl actBusinessService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IYgdabService ygdabService;
    @Autowired
    private IBjRecruitmentApplicationService applicationService;
    @Resource
    BjYgruzhiMapper bjYgruzhiMapper;
    @Resource
    BjQuitMapper bjQuitMapper;
    @Resource
    BjGwbdMapper bjGwbdMapper;
    @Autowired
    SignTableService signTableService;

    @Override
    public List<Map<String,String>> createAndGetFile(String procInstId,String ygid,String num) throws IOException {
        ActBusiness actBusiness=actBusinessService.findByProcInstId(procInstId).get(0);
        HistoricProcessInstance historicProcessInstance =historyService.createHistoricProcessInstanceQuery().processInstanceId(procInstId).list().get(0);
        //获取业务id
        String table_id=actBusiness.getTableId();
        //流程名称
        String name = historicProcessInstance.getName();
        BjIdcardfk bjIdcardfk=bjIdcardfkService.getById(table_id);
        List<Map<String,String>> fileList=new ArrayList<>();
        File file=new File("D:\\Users\\file\\附件.xlsx");
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        //新的
        if(name.equals("员工入职申请"))
            name = "员工入职申请NEW";

        if(name.equals("员工入职申请")){
            //获取表单数据
            String ruzhiTableIds[]=bjIdcardfk.getRuzhiJson().split(",");
            //获取表格数据
            Map<String,Object> params=new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bjIdcardfk.getCreateTime());
            params.put("year",calendar.get(Calendar.YEAR));
            params.put("month",(calendar.get(Calendar.MONTH)+1));
            List<Map<String,Object>> mapList=new ArrayList<>();
            TemplateExportParams templateExportParams = new TemplateExportParams();
            for(int i=0;i<ruzhiTableIds.length;i++){
                BjYgruzhi bjYgruzhi=bjYgruzhiMapper.selectById(ruzhiTableIds[i]);
                String yuangongid=bjYgruzhi.getYgid();
                List laozi=ygdabService.getLaoZiGongZiByUserId(yuangongid);
                String zjjg="";//中介机构
                String ygly="";//用工来源
                if(laozi.isEmpty()==false){
                    Map laozimap=(Map)laozi.get(0);
                    zjjg=laozimap.get("ZJJG").toString();
                    ygly=laozimap.get("YGLY").toString();
                }
                int seq=i+1;
                Map<String,Object> map=new HashMap<>();
                map.put("seq",String.valueOf(seq));
                map.put("name",bjYgruzhi.getName());
                map.put("sex",bjYgruzhi.getSex().equals("1")?"男":"女");
                map.put("age",calculateAge(bjYgruzhi.getSfzh()));
                map.put("gwname",bjYgruzhi.getGwname());
                map.put("zdwname",bjYgruzhi.getZidanwei());
                map.put("ygly",ygly);
                map.put("zyreason",bjYgruzhi.getZyreason());
                map.put("zydate",bjYgruzhi.getZydate());
                map.put("zjjg",zjjg);
                map.put("sfzh",bjYgruzhi.getSfzh());
                map.put("qxdate",bjYgruzhi.getQxdate());
                map.put("remark",bjYgruzhi.getRemark());
                mapList.add(map);

            }
            params.put("maplist",mapList);
            //获取签章信息
            List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
            if(signTableList.size()>0){
                String[] usertasks={"usertask1","usertask2","usertask3","usertask4"};
                String[] data=new String[signTableList.size()];
                for(int k=0;k<signTableList.size();k++){
                    SignTable signTable=signTableList.get(k);
                    String task_def_key=signTable.getTaskDefKey();
                    String userId=signTable.getUserId();
                    String endTime=signTable.getEndTime();

                    //插入签章图片
                    ImageEntity image=new ImageEntity();
                    //image.setHeight(50);
                   // image.setWidth(200);
                   // image.setRowspan(3);
                    image.setColspan(3);
                    image.setUrl("test.jpeg");
                    image.setType(ImageEntity.URL);//类型
                    params.put(task_def_key,image);
                    String date_key="";
                    if(task_def_key.equals("usertask1")){
                        date_key="date1";
                    }
                    if(task_def_key.equals("usertask2")){
                        date_key="date2";
                    }
                    if(task_def_key.equals("usertask3")){
                        date_key="date3";
                    }
                    if(task_def_key.equals("usertask4")){
                        date_key="date4";
                    }
                    params.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                    data[k]=task_def_key;
                }
                Set<String> d_key=diff(data,usertasks);
                if(!d_key.isEmpty()){
                   for(String d:d_key) {
                       if(d.equals("usertask1")){
                           params.put("usertask1","");
                           params.put("date1","年 月 日");
                       }
                       if(d.equals("usertask2")){
                           params.put("usertask2","");
                           params.put("date2","年 月 日");
                       }
                       if(d.equals("usertask3")){
                           params.put("usertask3","");
                           params.put("date3","年 月 日");
                       }
                       if(d.equals("usertask4")){
                           params.put("usertask4","");
                           params.put("date4","年 月 日");
                       }
                   }
                }
            }else{
                params.put("usertask1","");
                params.put("usertask2","");
                params.put("usertask3","");
                params.put("usertask4","");
                params.put("date1","年 月 日");
                params.put("date2","年 月 日");
                params.put("date3","年 月 日");
                params.put("date4","年 月 日");
            }
            String filePath = ClassUtils.getDefaultClassLoader().getResource("ruzhi.xlsx").getPath();
            String outpath="D:\\Users\\file\\劳务用工增员情况备案表.xlsx";
            try {
                templateExportParams.setTemplateUrl(filePath);
                Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams,params);
                FileOutputStream fos = new FileOutputStream(outpath);
                workbook.write(fos);
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            Map<String,String> filemap=new HashMap<>();
            filemap.put("key","劳务用工增员情况备案表");
            filemap.put("value","D:\\Users\\file\\劳务用工增员情况备案表.xlsx");
            fileList.add(filemap);

        }

        if(name.equals("员工入职申请NEW")){
            //获取表单数据
            name = "员工入职申请";
            String ruzhiTableIds[]=bjIdcardfk.getRuzhiJson().split(",");
            //获取表格数据
            Map<String,Object> params=new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bjIdcardfk.getCreateTime());
            params.put("year",calendar.get(Calendar.YEAR));
            params.put("month",(calendar.get(Calendar.MONTH)+1));
            List<Map<String,Object>> mapList=new ArrayList<>();
            TemplateExportParams templateExportParams = new TemplateExportParams();
            for(int i=0;i<ruzhiTableIds.length;i++){
                BjYgruzhi bjYgruzhi=bjYgruzhiMapper.selectById(ruzhiTableIds[i]);
                String yuangongid=bjYgruzhi.getYgid();
                List laozi=ygdabService.getLaoZiGongZiByUserId(yuangongid);
                String zjjg="";//中介机构
                String ygly="";//用工来源
                if(laozi.isEmpty()==false){
                    Map laozimap=(Map)laozi.get(0);
                    zjjg=laozimap.get("ZJJG").toString();
                    ygly=laozimap.get("YGLY").toString();
                }
                int seq=i+1;
                Map<String,Object> map=new HashMap<>();
                map.put("seq",String.valueOf(seq));
                map.put("name",bjYgruzhi.getName());
                map.put("sex",bjYgruzhi.getSex().equals("1")?"男":"女");
                map.put("age",calculateAge(bjYgruzhi.getSfzh()));
                map.put("gwname",bjYgruzhi.getGwname());
                map.put("zdwname",bjYgruzhi.getZidanwei());
                map.put("ygly",ygly);
                map.put("zyreason",bjYgruzhi.getZyreason());
                map.put("zydate",bjYgruzhi.getZydate());
                map.put("zjjg",zjjg);
                map.put("sfzh",bjYgruzhi.getSfzh());
                map.put("qxdate",bjYgruzhi.getQxdate());
                map.put("remark",bjYgruzhi.getRemark());
                mapList.add(map);
            }

            params.put("maplist",mapList);
            Map<String, BufferedImage> cellMap5 =new HashMap<>();

            //获取签章信息
            List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
            if(signTableList.size()>0){
                String[] usertasks={"usertask1","usertask2","usertask3","usertask4"};
                String[] data=new String[signTableList.size()];
                for(int k=0;k<signTableList.size();k++){
                    SignTable signTable=signTableList.get(k);
                    String task_def_key=signTable.getTaskDefKey();
                    //String userId=signTable.getUserId();
                    String endTime=signTable.getEndTime();
                    //插入签章图片
                    ImageEntity image=new ImageEntity();
                    image.setColspan(3);
                    image.setUrl("test.jpeg");
                    image.setType(ImageEntity.URL);//类型

                    //File file2 = (new File("/test.jpeg"));
                    String filePath = BjCreateFileServiceImpl.class.getClassLoader().getResource("test.jpeg").getFile();
                    BufferedImage bufferImg = ImageIO.read(new File(filePath));
                   // InputStream is = this.getClass().getResourceAsStream("/test.jpeg");

                   cellMap5.put(task_def_key,bufferImg);

                    params.put(task_def_key,image);
                    String No = (k+1)+"";
                    String date_key = "date"+No;
                    params.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                    data[k]=task_def_key;
                }
                Set<String> d_key = diff(data,usertasks);
                if(!d_key.isEmpty()){
                    for(String d:d_key) {
                        params.put(d,"");
                        params.put("date"+d.split("usertask")[1],"年 月 日");
                    }
                }
            }else{
                params.put("usertask1","");
                params.put("usertask2","");
                params.put("usertask3","");
                params.put("usertask4","");
                params.put("date1","年 月 日");
                params.put("date2","年 月 日");
                params.put("date3","年 月 日");
                params.put("date4","年 月 日");
            }

            //按劳务公司分组 变成多个List
            Map<String,List<Map<String,Object>>> sheetListMap = groupByList(mapList);


            SXSSFWorkbook wb = new SXSSFWorkbook(200);
            XSSFCellStyle rowStyle = PoiUtil.setXSSFCellStyleRow(wb,(short)12);
            for (String sheetName : sheetListMap.keySet()){
                int rows = 0;

                Map<String, String> cellMapNull =new HashMap<>();
                cellMapNull.put("0", "");
                cellMapNull.put("1", "");
                cellMapNull.put("2", "");
                cellMapNull.put("3", "");
                cellMapNull.put("4", "");
                cellMapNull.put("5", "");
                cellMapNull.put("6", "");
                cellMapNull.put("7", "");
                cellMapNull.put("8", "");
                cellMapNull.put("9", "");
                cellMapNull.put("10", "");
                cellMapNull.put("11", "");
                cellMapNull.put("12", "");
                XSSFCellStyle headerStyle = PoiUtil.setXSSFCellStyleRow(wb,(short)20);
                SXSSFSheet sheet = wb.createSheet(sheetName);
                //Map<String, String> rowMap =new HashMap<>();
                List<String> rowMap = new ArrayList<>();
                //表头
                Map<String, String> cellMap1 =new HashMap<>();
                cellMap1.put("0", params.get("year")+ "年" + params.get("month") +"月劳务用工增员情况备案表");
                Row row = ExcelExportUtils.customHeader(headerStyle, sheet, rows,cellMap1);
                rowMap.add(rows+","+rows+",0,12");
                XSSFCellStyle customXSSFCellStyle =	PoiUtil.customXSSFCellStyleHeader(wb, HorizontalAlignment.CENTER,
                        VerticalAlignment.CENTER,
                        BorderStyle.THIN,
                        BorderStyle.THIN,
                        BorderStyle.THIN,
                        BorderStyle.THIN,
                        true);
                rows = rows + 2;
                row = ExcelExportUtils.customHeader2(customXSSFCellStyle, Constants.YGZYBAB, rows,sheet);
                rows = rows + 1;
                rows = ExcelExportUtils.customDataRow(sheetListMap.get(sheetName), Constants.YGZYBAB, rowStyle, sheet,rows);
                int rowNum = sheet.getPhysicalNumberOfRows();//获得总行数
                System.out.println( "rowNum========"+rowNum+"rows===="+rows);
                //表格title
                Map<String, String> cellMap3 =new HashMap<>();
                cellMap3.put("0", "");
                cellMap3.put("1", "用工单位");
                cellMap3.put("4", "综合办公室");
                cellMap3.put("7", "主管领导");
                cellMap3.put("10", "公司总经理");

                rows = rows + 1;
                rowMap.add(rows+","+rows+",1,3");
                rowMap.add(rows+","+rows+",4,6");
                rowMap.add(rows+","+rows+",7,9");
                rowMap.add(rows+","+rows+",10,12");

                row = ExcelExportUtils.customHeader(customXSSFCellStyle, sheet, rows, cellMap3);

                rows = rows + 1;
                Map<String, String> cellMap4 =new HashMap<>();
                cellMap4.put("0", "审查确认");
                rowMap.add(rows+","+rows+",1,3");
                rowMap.add(rows+","+rows+",4,6");
                rowMap.add(rows+","+rows+",7,9");
                rowMap.add(rows+","+rows+",10,12");

                int a= rows + 1;
                //表格content
                row = ExcelExportUtils.customHeader(customXSSFCellStyle, sheet, rows, cellMap4);
                //实体加一个空行，加进去了，但是没有格式
                row = ExcelExportUtils.customHeader(customXSSFCellStyle, sheet, rows, cellMapNull);
                //电子章
                row.setHeight((short)(10*256));
                row = ExcelExportUtils.customHeaderPicture(wb, a ,sheet, cellMap5);


                rows = rows + 1;
                Map<String, String> cellMap6 =new HashMap<>();
                cellMap6.put("1", params.get("date1").toString());
                cellMap6.put("4",params.get("date2").toString());
                cellMap6.put("7",params.get("date3").toString());
                cellMap6.put("10", params.get("date4").toString());

                row = ExcelExportUtils.customHeader(customXSSFCellStyle, sheet, rows, cellMap6);

                ExcelExportUtils.columnWidth(Constants.YGZYBAB, sheet);

                ExcelExportUtils.customMerge(wb, sheet,rowMap);
            }

            String filePath = ClassUtils.getDefaultClassLoader().getResource("ruzhi.xlsx").getPath();

            String outpath="D:\\Users\\file\\劳务用工增员情况备案表.xlsx";
            try {
                templateExportParams.setTemplateUrl(filePath);
                FileOutputStream fos = new FileOutputStream(outpath);
                wb.write(fos);
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            Map<String,String> filemap=new HashMap<>();
            filemap.put("key","劳务用工增员情况备案表");
            filemap.put("value","D:\\Users\\file\\劳务用工增员情况备案表.xlsx");
            fileList.add(filemap);

        }

        if(name.equals("招工申请")){
            BjRecruitmentApplication application=applicationService.getById(table_id);
            Map<String,Object> params=new HashMap<>();
            params.put("sqdw",application.getSqdw());
            params.put("sqgw",application.getSqgw());
            params.put("jbren",application.getJbren());
            params.put("sqdate",application.getSqdate());
            params.put("gwgzbz",application.getGwgzbz());
            params.put("zwms1",application.getZwms1());
            params.put("zwms2",application.getZwms2());
            params.put("zwms3",application.getZwms3());
            params.put("rzzgRenshu",application.getRzzgRenshu());
            params.put("rzzgAge",application.getRzzgAge());
            params.put("rzzgSex",application.getRzzgSex());
            params.put("rzzgXl",application.getRzzgXl());
            params.put("rzzgZy",application.getRzzgZy());
            params.put("rzzgJy",application.getRzzgJy());
            params.put("nlsz",application.getNlsz());
            params.put("zpyy",application.getZpyy());
            params.put("ygqx","自"+application.getYgstartdt().split("-")[0]+"年"+application.getYgstartdt().split("-")[1]+"月"+application.getYgstartdt().split("-")[2]+"日至"+application.getYgenddt().split("-")[0]+"年"+application.getYgenddt().split("-")[1]+"月"+application.getYgenddt().split("-")[2]+"日");
            //获取签章信息
            List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
            if(signTableList.size()>0){
                String[] usertasks={"usertask1","usertask2","usertask3","usertask4"};
                String[] data=new String[signTableList.size()];
                for(int k=0;k<signTableList.size();k++){
                    SignTable signTable=signTableList.get(k);
                    String taskId=signTable.getTaskId();
                    String task_def_key=signTable.getTaskDefKey();
                    String userId=signTable.getUserId();
                    String endTime=signTable.getEndTime();

                    //21-11-17 hwq 优化一下审批和签章
                    List<Comment> comments = taskService.getTaskComments(taskId, "comment");
                    String kNo = (k+1)+"";
                    ImageEntity image=new ImageEntity();
                    image.setHeight(50);
                    image.setWidth(80);
                    image.setUrl("test.jpeg");
                    image.setType(ImageEntity.URL);//类型
                    params.put("sign"+kNo,image);
                    String date_key="date"+kNo;
                    if(comments!=null&&comments.size()>0){
                        params.put("option"+kNo,comments.get(0).getFullMessage());
                    }

                    /*
                    if(task_def_key.equals("usertask1")){
                        //插入签章图片
                        ImageEntity image = new ImageEntity();
                        image.setHeight(50);
                        image.setWidth(80);
                        image.setUrl("test.jpeg");
                        image.setType(ImageEntity.URL);//类型
                        params.put("sign1",image);
                        date_key="date1";
                        if(comments!=null&&comments.size()>0){
                            params.put("option1",comments.get(0).getFullMessage());
                        }
                    }
                    if(task_def_key.equals("usertask2")){
                        if(comments!=null&&comments.size()>0){
                            params.put("option2",comments.get(0).getFullMessage());
                        }
                        date_key="date2";
                    }
                    if(task_def_key.equals("usertask3")){
                        if(comments!=null&&comments.size()>0){
                            params.put("option3",comments.get(0).getFullMessage());
                        }
                        date_key="date3";
                    }
                    if(task_def_key.equals("usertask4")){
                        if(comments!=null&&comments.size()>0){
                            params.put("option4",comments.get(0).getFullMessage());
                        }
                        date_key="date4";
                    }*/
                    params.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                    data[k]=task_def_key;
                }
                Set<String> d_key=diff(data,usertasks);
                if(!d_key.isEmpty()){
                    for(String d:d_key) {
                        if(d.equals("usertask1")){
                            params.put("sign1","");
                            params.put("date1","年 月 日");
                        }
                        if(d.equals("usertask2")){
                            params.put("option2","");
                            params.put("date2","年 月 日");
                        }
                        if(d.equals("usertask3")){
                            params.put("option3","");
                            params.put("date3","年 月 日");
                        }
                        if(d.equals("usertask4")){
                            params.put("option4","");
                            params.put("date4","年 月 日");
                        }
                    }
                }
            }else{
                params.put("sign1","");
                params.put("option2","");
                params.put("option3","");
                params.put("option4","");
                params.put("date1","年 月 日");
                params.put("date2","年 月 日");
                params.put("date3","年 月 日");
                params.put("date4","年 月 日");
            }
            String filePath = ClassUtils.getDefaultClassLoader().getResource("zgsq.docx").getPath();
            String outpath="D:\\Users\\file\\招工申请表.docx";
            try {
                XWPFDocument doc = WordExportUtil.exportWord07(filePath, params);
                FileOutputStream fos = new FileOutputStream(outpath);
                doc.write(fos);
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            Map<String,String> filemap=new HashMap<>();
            filemap.put("key","招工申请表");
            filemap.put("value","D:\\Users\\file\\招工申请表.docx");
            fileList.add(filemap);
        }

        if(name.equals("员工离职申请")){
            //获取表单数据
            String lizhiTableIds[]=bjIdcardfk.getLizhiJson().split(",");
            String filepath1=ClassUtils.getDefaultClassLoader().getResource("yglizhisq.docx").getPath();
            String filepath2=ClassUtils.getDefaultClassLoader().getResource("jianyuanbeian.xlsx").getPath();
            String filepath3=ClassUtils.getDefaultClassLoader().getResource("cituihan.docx").getPath();
            List<Map<String,Object>> mapList=new ArrayList<>();
            Map<String,List<BjQuit>> cituihanMap=new HashMap<>();
            Map<String,BjQuit> map11=new HashMap<>();
            for(int i=0;i<lizhiTableIds.length;i++){
                BjQuit bjQuit=bjQuitMapper.selectById(lizhiTableIds[i]);
                String yuangongid=bjQuit.getYgid();
                List laozi=ygdabService.getLaoZiGongZiByUserId(yuangongid);
                String zjjg="";//中介机构
                String ygly="";//用工来源
                if(laozi.isEmpty()==false){
                    Map laozimap=(Map)laozi.get(0);
                    zjjg=laozimap.get("ZJJG").toString();
                    ygly=laozimap.get("YGLY").toString();
                }
                if(cituihanMap.containsKey(zjjg)){
                    List<BjQuit> bjQuitList= cituihanMap.get(zjjg);
                    bjQuitList.add(bjQuit);
                }else{
                    List<BjQuit> bjQuitList=new ArrayList<>();
                    bjQuitList.add(bjQuit);
                    cituihanMap.put(zjjg,bjQuitList);
                }

                int seq=i+1;
                Map<String,Object> map=new HashMap<>();
                map.put("seq",String.valueOf(seq));
                map.put("name",bjQuit.getName());
                map.put("sex",bjQuit.getSex().equals("1")?"男":"女");
                map.put("age",calculateAge(bjQuit.getSfzh()));
                map.put("gwname",bjQuit.getGwname());
                map.put("zdwname",bjQuit.getZdwname());
                map.put("ygly",ygly);
                map.put("jyreason",bjQuit.getJyreason());
                map.put("jydate",bjQuit.getJydate());
                map.put("zjjg",zjjg);
                map.put("sfzh",bjQuit.getSfzh());
                map.put("txsj",bjQuit.getTxdate());
                map.put("remark",bjQuit.getRemark());
                mapList.add(map);

                String fileoutpath="D:\\Users\\file\\员工离职申请表_"+bjQuit.getName()+".docx";
                //员工离职申请表
                Map<String,Object> params2=new HashMap<>();
                params2.put("name",bjQuit.getName());
                params2.put("bumen",bjQuit.getBumen());
                params2.put("zhiwu",bjQuit.getGwname());
                if(StringUtils.isNotEmpty(bjQuit.getRzriqi())){
                    params2.put("ruzhidate",bjQuit.getRzriqi().split("-")[0]+"年"+bjQuit.getRzriqi().split("-")[1]+"月"+bjQuit.getRzriqi().split("-")[2]+"日");
                }else{
                    params2.put("ruzhidate","");
                }

                params2.put("xwdate",bjQuit.getXwdate().split("-")[0]+"年"+bjQuit.getXwdate().split("-")[1]+"月"+bjQuit.getXwdate().split("-")[2]+"日");
                params2.put("lizhireason",bjQuit.getLizhireason());
                params2.put("lastworkdate",bjQuit.getLastworkdate().split("-")[0]+"年"+bjQuit.getLastworkdate().split("-")[1]+"月"+bjQuit.getLastworkdate().split("-")[2]+"日");
                params2.put("mtjilu",bjQuit.getMtjilu());
                params2.put("jzdate",bjQuit.getJzdate().split("-")[0]+"年"+bjQuit.getJzdate().split("-")[1]+"月"+bjQuit.getJzdate().split("-")[2]+"日");

                //获取签章信息
                List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
                if(signTableList.size()>0){
                    String[] usertasks={"usertask1","usertask2","usertask3"};
                    String[] data=new String[signTableList.size()];
                    for(int k=0;k<signTableList.size();k++){
                        SignTable signTable=signTableList.get(k);
                        String task_def_key=signTable.getTaskDefKey();
                        String userId=signTable.getUserId();
                        String endTime=signTable.getEndTime();

                        //插入签章图片
                        ImageEntity image=new ImageEntity();
                        image.setHeight(80);
                        image.setWidth(150);
                        image.setUrl("test.jpeg");
                        image.setType(ImageEntity.URL);//类型
                        params2.put(task_def_key,image);
                        String date_key="";
                        if(task_def_key.equals("usertask1")){
                            date_key="date1";
                        }
                        if(task_def_key.equals("usertask2")){
                            date_key="date2";
                        }
                        if(task_def_key.equals("usertask3")){
                            date_key="date3";
                        }

                        params2.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                        data[k]=task_def_key;
                    }
                    Set<String> d_key=diff(data,usertasks);
                    if(!d_key.isEmpty()){
                        for(String d:d_key) {
                            if(d.equals("usertask1")){
                                params2.put("usertask1","");
                                params2.put("date1","年 月 日");
                            }
                            if(d.equals("usertask2")){
                                params2.put("usertask2","");
                                params2.put("date2","年 月 日");
                            }
                            if(d.equals("usertask3")){
                                params2.put("usertask3","");
                                params2.put("date3","年 月 日");
                            }
                        }
                    }
                }else{
                    params2.put("usertask1","");
                    params2.put("usertask2","");
                    params2.put("usertask3","");
                    params2.put("date1","年 月 日");
                    params2.put("date2","年 月 日");
                    params2.put("date3","年 月 日");
                }

                try {
                    XWPFDocument doc1 = WordExportUtil.exportWord07(filepath1, params2);
                    FileOutputStream fos1 = new FileOutputStream(fileoutpath);
                    doc1.write(fos1);
                    fos1.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

                if(StringUtils.isNotEmpty(bjQuit.getImage1())){
                    GenerateImage("image1",bjQuit.getImage1(),"D:\\Users\\file\\",bjQuit.getName());
                }
                if(StringUtils.isNotEmpty(bjQuit.getImage2())){
                    GenerateImage("image2",bjQuit.getImage2(),"D:\\Users\\file\\",bjQuit.getName());
                }
                if(StringUtils.isNotEmpty(bjQuit.getImage3())){
                    GenerateImage("image3",bjQuit.getImage3(),"D:\\Users\\file\\",bjQuit.getName());
                }
                map11.put(yuangongid,bjQuit);
            }

            for (Map.Entry<String,List<BjQuit>> entry : cituihanMap.entrySet()) {
              String path_citui="D:\\Users\\file\\劳务工离职函_"+entry.getKey()+".docx";
              List<BjQuit> list=entry.getValue();
             //劳务工辞退函
              Map<String,Object> params3=new HashMap<>();
              params3.put("zjjg",entry.getKey());
              params3.put("num",list.size());
              Ygdab ygdab=ygdabService.getById(list.get(0).getYgid());
              params3.put("gzdw",ygdab.getDwname());
              params3.put("date1",new SimpleDateFormat("yyyy年MM月dd日").format(bjIdcardfk.getCreateTime()));
              params3.put("namestr",list.get(0).getName());
              List<Map<String,Object>> mapList3=new ArrayList<>();
              for(BjQuit bjQuit:list){
                  Map<String,Object> map3=new HashMap();
                  map3.put("name",bjQuit.getName());
                  map3.put("sex",bjQuit.getSex().equals("1")?"男":"女");
                  map3.put("zw",bjQuit.getZhiwu());
                  map3.put("ctdate",new SimpleDateFormat("yyyy-MM-dd").format(bjIdcardfk.getCreateTime()));
                  mapList3.add(map3);
              }
              if(list.size()<29){
                  int size=29-list.size();
                  for(int p=0;p<size;p++){
                      Map<String,Object> map3=new HashMap();
                      map3.put("name","");
                      map3.put("sex","");
                      map3.put("zw","");
                      map3.put("ctdate","");
                      mapList3.add(map3);
                  }
              }
              params3.put("maplist",mapList3);
                try {
                    XWPFDocument doc3 = WordExportUtil.exportWord07(filepath3, params3);
                    FileOutputStream fos3 = new FileOutputStream(path_citui);
                    doc3.write(fos3);
                    fos3.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            //减员情况备案表参数
            Map<String,Object> params1=new HashMap<>();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(bjIdcardfk.getCreateTime());
            params1.put("year",calendar.get(Calendar.YEAR));
            params1.put("month",(calendar.get(Calendar.MONTH)+1));
            params1.put("maplist",mapList);
            //获取签章信息
            List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
            if(signTableList.size()>0){
                String[] usertasks={"usertask1","usertask2","usertask3","usertask4"};
                String[] data=new String[signTableList.size()];
                for(int k=0;k<signTableList.size();k++){
                    SignTable signTable=signTableList.get(k);
                    String task_def_key=signTable.getTaskDefKey();
                    String userId=signTable.getUserId();
                    String endTime=signTable.getEndTime();

                    //插入签章图片
                    ImageEntity image=new ImageEntity();
                    image.setColspan(3);
                    image.setUrl("test.jpeg");
                    image.setType(ImageEntity.URL);//类型
                    params1.put(task_def_key,image);
                    String date_key="";
                    if(task_def_key.equals("usertask1")){
                        date_key="date1";
                    }
                    if(task_def_key.equals("usertask2")){
                        date_key="date2";
                    }
                    if(task_def_key.equals("usertask3")){
                        date_key="date3";
                    }
                    if(task_def_key.equals("usertask4")){
                        date_key="date4";
                    }
                    params1.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                    data[k]=task_def_key;
                }
                Set<String> d_key=diff(data,usertasks);
                if(!d_key.isEmpty()){
                    for(String d:d_key) {
                        if(d.equals("usertask1")){
                            params1.put("usertask1","");
                            params1.put("date1","年 月 日");
                        }
                        if(d.equals("usertask2")){
                            params1.put("usertask2","");
                            params1.put("date2","年 月 日");
                        }
                        if(d.equals("usertask3")){
                            params1.put("usertask3","");
                            params1.put("date3","年 月 日");
                        }
                        if(d.equals("usertask4")){
                            params1.put("usertask4","");
                            params1.put("date4","年 月 日");
                        }
                    }
                }
            }else{
                params1.put("usertask1","");
                params1.put("usertask2","");
                params1.put("usertask3","");
                params1.put("usertask4","");
                params1.put("date1","年 月 日");
                params1.put("date2","年 月 日");
                params1.put("date3","年 月 日");
                params1.put("date4","年 月 日");
            }
            String outpath="D:\\Users\\file\\劳务用工减员情况备案表.xlsx";
            try {
                TemplateExportParams templateExportParams = new TemplateExportParams();
                templateExportParams.setTemplateUrl(filepath2);
                Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams,params1);
                FileOutputStream fos = new FileOutputStream(outpath);
                workbook.write(fos);
                fos.close();
            }catch (Exception e){
                e.printStackTrace();
            }

            if(num.equals("0")){
                Map<String,String> filemap1=new HashMap<>();
                filemap1.put("key","劳务用工减员情况备案表");
                filemap1.put("value","D:\\Users\\file\\劳务用工减员情况备案表.xlsx");
                fileList.add(filemap1);
                Ygdab ygdab=ygdabService.getById(ygid);
                Map<String,String> filemap2=new HashMap<>();
                filemap2.put("key","员工离职申请表_"+ygdab.getName());
                filemap2.put("value","D:\\Users\\file\\员工离职申请表_"+ygdab.getName()+".docx");
                fileList.add(filemap2);
                List laozi=ygdabService.getLaoZiGongZiByUserId(ygid);
                String zjjg="";//中介机构
                if(laozi.isEmpty()==false){
                    Map laozimap=(Map)laozi.get(0);
                    zjjg=laozimap.get("ZJJG").toString();
                }
                Map<String,String> filemap3=new HashMap<>();
                filemap3.put("key","劳务工离职函_"+zjjg);
                filemap3.put("value","D:\\Users\\file\\劳务工离职函_"+zjjg+".docx");
                fileList.add(filemap3);
            }
            if(num.equals("1")){
                //外加3个附件
                BjQuit bjQuit=map11.get(ygid);
                if(StringUtils.isNotEmpty(bjQuit.getImage1())){
                    Map<String,String> filemap4=new HashMap<>();
                    filemap4.put("key","员工离职交接表");
                    filemap4.put("value","D:\\Users\\file\\员工离职交接表_"+bjQuit.getName()+"."+getExt(bjQuit.getImage1()));
                    fileList.add(filemap4);
                }
                if(StringUtils.isNotEmpty(bjQuit.getImage2())){
                    Map<String,String> filemap5=new HashMap<>();
                    filemap5.put("key","离职人员个人劳保服装发放情况确认单");
                    filemap5.put("value","D:\\Users\\file\\离职人员个人劳保服装发放情况确认单_"+bjQuit.getName()+"."+getExt(bjQuit.getImage2()));
                    fileList.add(filemap5);
                }
                if(StringUtils.isNotEmpty(bjQuit.getImage3())){
                    Map<String,String> filemap6=new HashMap<>();
                    filemap6.put("key","个人劳动保护用品登记卡");
                    filemap6.put("value","D:\\Users\\file\\个人劳动保护用品登记卡_"+bjQuit.getName()+"."+getExt(bjQuit.getImage3()));
                    fileList.add(filemap6);
                }
            }

        }

        if(name.equals("员工调动变动申请")){
            //获取表单数据
            String biandongid=bjIdcardfk.getBiandongJson();
            BjGwbd bjGwbd=bjGwbdMapper.selectById(biandongid);
            Map<String,Object> params=new HashMap<>();
            // Ygdab ygdab=ygdabService.getById(bjGwbd.getYgid());
            String type=bjGwbd.getType();
            params.put("filldate",new SimpleDateFormat("yyyy年MM月dd日").format(bjIdcardfk.getCreateTime()));
            params.put("name",bjGwbd.getName());
            params.put("danwei",bjGwbd.getDwname());
            params.put("rzdate",bjGwbd.getRuzhidt());
            params.put("oldbumen",bjGwbd.getBmname());
            params.put("oldzw",bjGwbd.getZwgz());
            params.put("oldmain",bjGwbd.getOldmain());
            params.put("oldbasic",bjGwbd.getOldbasic());
            params.put("newbumen",bjGwbd.getNewbm());
            params.put("newgw",bjGwbd.getNewgw());
            params.put("newmain",bjGwbd.getNewmain());
            if(type.equals("1")){
                //合同
                params.put("new1",bjGwbd.getNewjbgz());
                params.put("new2",bjGwbd.getJiaotongbutie());
                params.put("new3",bjGwbd.getTongxunfei());
                params.put("new4",bjGwbd.getShbt());
                params.put("new5",bjGwbd.getFangbu());
                params.put("new6",bjGwbd.getGljt());
            }else{
                //劳务
                params.put("new1",bjGwbd.getNewjbgz());
                params.put("new2",bjGwbd.getGwgz());
                params.put("new3",bjGwbd.getFdgz());
                String yl=bjGwbd.getYldaijiao();
                if(yl.equals("1")){
                   params.put("new4","代缴☑ 不代缴□");
                   params.put("new5",bjGwbd.getYldaijiaoje());
                }else{
                    params.put("new4","代缴□ 不代缴☑");
                    params.put("new5","");
                }
                String sy=bjGwbd.getShiyedaijiao();
                if(sy.equals("1")){
                    params.put("new6","代缴☑ 不代缴□");
                    params.put("new7",bjGwbd.getShiyedaijiaoje());
                }else{
                    params.put("new6","代缴□ 不代缴☑");
                    params.put("new7","");
                }
                String yliao=bjGwbd.getYldaijiao();
                if(yliao.equals("1")){
                    params.put("new8","代缴☑ 不代缴□");
                    params.put("new9",bjGwbd.getYldaijiaoje());
                }else{
                    params.put("new8","代缴□ 不代缴☑");
                    params.put("new9","");
                }
            }
            params.put("reason",bjGwbd.getBgyuanyin());
            params.put("sxdate",StringUtils.isNotEmpty(bjGwbd.getSxdt())?bjGwbd.getSxdt().split("-")[0]+"年"+bjGwbd.getSxdt().split("-")[1]+"月"+bjGwbd.getSxdt().split("-")[2]+"日":"年  月  日");
            //获取签章信息
            List<SignTable> signTableList=signTableService.getDataListByProceId(procInstId);
            if(signTableList.size()>0){
                String[] usertasks={"usertask1","usertask2","usertask3","usertask4"};
                String[] data=new String[signTableList.size()];
                for(int k=0;k<signTableList.size();k++){
                    SignTable signTable=signTableList.get(k);
                    String taskId=signTable.getTaskId();
                    String task_def_key=signTable.getTaskDefKey();
                    String userId=signTable.getUserId();
                    String endTime=signTable.getEndTime();

                    //插入签章图片
                    ImageEntity image=new ImageEntity();
                    image.setHeight(50);
                    image.setWidth(80);
                    image.setUrl("test.jpeg");
                    image.setType(ImageEntity.URL);//类型
                    params.put(task_def_key,image);
                    String date_key="";
                    if(task_def_key.equals("usertask1")){
                        date_key="date1";
                    }
                    if(task_def_key.equals("usertask2")){
                        date_key="date2";
                    }
                    if(task_def_key.equals("usertask3")){
                        date_key="date3";
                    }
                    if(task_def_key.equals("usertask4")){
                        date_key="date4";
                    }
                    params.put(date_key,endTime.split("-")[0]+"年"+endTime.split("-")[1]+"月"+endTime.split("-")[2]+"日");
                    data[k]=task_def_key;
                }
                Set<String> d_key=diff(data,usertasks);
                if(!d_key.isEmpty()){
                    for(String d:d_key) {
                        if(d.equals("usertask1")){
                            params.put("usertask1","");
                            params.put("date1","年 月 日");
                        }
                        if(d.equals("usertask2")){
                            params.put("usertask2","");
                            params.put("date2","年 月 日");
                        }
                        if(d.equals("usertask3")){
                            params.put("usertask3","");
                            params.put("date3","年 月 日");
                        }
                        if(d.equals("usertask4")){
                            params.put("usertask4","");
                            params.put("date4","年 月 日");
                        }
                    }
                }

            }else{
                params.put("usertask1","");
                params.put("usertask2","");
                params.put("usertask3","");
                params.put("usertask4","");
                params.put("date1","年 月 日");
                params.put("date2","年 月 日");
                params.put("date3","年 月 日");
                params.put("date4","年 月 日");
            }
            String filePath="";
            String outpath="";
            String filename="";
            String filePath2 = "";
            String outpath2 = "";
            String filename2 = "";

            if(type.equals("1")){
                filename="合同化员工岗位变更单";
                filePath = ClassUtils.getDefaultClassLoader().getResource("htbd.docx").getPath();
                //String filepath1=ClassUtils.getDefaultClassLoader().getResource("yglizhisq.docx").getPath();
                outpath="D:\\Users\\file\\合同化员工岗位变更单.docx";

            }else{
                filename="劳务用工岗位变更单";
                filePath = ClassUtils.getDefaultClassLoader().getResource("lwbd.docx").getPath();
                //String filepath1=ClassUtils.getDefaultClassLoader().getResource("yglizhisq.docx").getPath();
                outpath="D:\\Users\\file\\劳务用工岗位变更单.docx";
            }
            filename2 = "岗位变更情况备案表";
            filePath2 = ClassUtils.getDefaultClassLoader().getResource("gbqkbab.xlsx").getPath();
            outpath2 = "D:\\Users\\file\\岗位变更情况备案表.xlsx";
            try {
                params.put("rep","1");
                params.put("sex",bjGwbd.getSex());
                params.put("age",bjGwbd.getAge());
                params.put("idcard",bjGwbd.getIdcard());
                params.put("bbsxdt",bjGwbd.getBbsxdt());
                XWPFDocument doc = WordExportUtil.exportWord07(filePath, params);
                FileOutputStream fos = new FileOutputStream(outpath);
                doc.write(fos);


                TemplateExportParams templateExportParams = new TemplateExportParams();
                templateExportParams.setTemplateUrl(filePath2);
                Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams,params);
                FileOutputStream fos2 = new FileOutputStream(outpath2);
                workbook.write(fos2);

                fos.close();
                fos2.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            Map<String,String> filemap=new HashMap<>();
            filemap.put("key",filename);
            filemap.put("value",outpath);
            fileList.add(filemap);
            Map<String,String> filemap2 = new HashMap<>();
            filemap2.put("key",filename2);
            filemap2.put("value",outpath2);
            fileList.add(filemap2);
        }
        return fileList;

    }

    public Set<String>  diff(String[] arr1, String[] arr2) {
        Set<String> set1 = new HashSet<>(Arrays.asList(arr1));
        Set<String> set2 = new HashSet<>(Arrays.asList(arr2));
        Set<String> set3 = new HashSet<>(set2);
        set3.addAll(set1);//set3 [100, 1, 2, 5, 7, -1]; set集合有去重特性
        set1.retainAll(set2);//retainAll():保留包含在指定 collection 中的元素；s1：[-1,1,2]
        set3.removeAll(set1);//	removeAll(); 移除 set 中那些包含在指定 collection 中的元素 ; s3 [3,4,100,5,7,-12,12]
        return set3;
    }

    public int calculateAge(String sfzh){
        int both_year=Integer.parseInt(sfzh.substring(6,10));
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR)-both_year;
    }

    public  void GenerateImage(String imagetype,String imgbaseStr,String outFilePath,String ygname)
    {   //对字节数组字符串进行Base64解码并生成图片
        String ext="";
        if(imgbaseStr.contains("image")){
            ext=imgbaseStr.substring(imgbaseStr.indexOf("/")+1,imgbaseStr.indexOf("/")+4);
        }
        if(imgbaseStr.contains("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
            ext="xlsx";
        }
        if(imgbaseStr.contains("application/vnd.ms-excel")){
            ext="xls";
        }
        String filename="";
        if(imagetype.equals("image1")){
            filename="员工离职交接表";
        }
        if(imagetype.equals("image2")){
            filename="离职人员个人劳保服装发放情况确认单";
        }
        if(imagetype.equals("image3")){
            filename="个人劳动保护用品登记卡";
        }

        byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(imgbaseStr.substring(imgbaseStr.indexOf(",")+1));
        for (int i = 0; i < bytes.length; ++i) {
            if (bytes[i] < 0) {// 调整异常数据
                bytes[i] += 256;
            }
        }
        String imgFilePath = outFilePath+"\\"+filename+"_"+ygname+"."+ext;//新生成的图片
        System.out.println(imgFilePath);
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getExt(String imgBaseStr){
        String ext="";
        if(imgBaseStr.contains("image")){
            ext=imgBaseStr.substring(imgBaseStr.indexOf("/")+1,imgBaseStr.indexOf("/")+4);
        }
        if(imgBaseStr.contains("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
            ext="xlsx";
        }
        if(imgBaseStr.contains("application/vnd.ms-excel")){
            ext="xls";
        }
        return ext;
    }
    public static Map<String,List<Map<String,Object>>> groupByList(List<Map<String,Object>> mapList){
        Map<String,List<Map<String,Object>>> backmap1 = new TreeMap<>();
        for(Map<String,Object> son : mapList){
            String key = son.get("zjjg").toString();
            if(backmap1.containsKey(key)) {
                //map中存在以此id作为的key，将数据存放当前key的map中
                backmap1.get(key).add(son);
            } else {
                //map中不存在以此id作为的key，新建key用来存放数据
                List<Map<String,Object>> sonList = new java.util.ArrayList<>();
                sonList.add(son);
                backmap1.put(key, sonList);
            }
        }

        return backmap1;
    }

}

